﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      ACR RoleManagementHelper 
// Created By:     Tingrong Shi (trshi@wicresoft.com)
// Created Date:   2011-1-27
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using ASBCC.Database.EntityFramework;

namespace ASBCC.Business
{
    public static class RoleManagementHelper
    {
        /// <summary>
        /// 插入一个Role及其对应的page和menu
        /// </summary>
        public static void OnRoleInserting(ObjectContext dc, Role role, string pageList, string menuList, string belongsTo)
        {
            if (belongsTo != null)
            {
                role.BelongsTo = belongsTo;
                if (belongsTo == SystemModule.Admin.ToString())
                {
                    var menus = dc.CreateQuery<Menu>("[Menus]");
                    foreach (var menu in menus)
                        role.Menus.Add(menu);
                }
            }

            if (menuList != null)
            {
                var menus = dc.CreateQuery<Menu>("[Menus]");
                foreach (var menu in menuList.Split(','))
                {
                    int menuID = int.Parse(menu);
                    var entity = menus.First(p => p.MenuID == menuID);
                    //判断menu是否为3级菜单，待修改
                    if (!String.IsNullOrEmpty(entity.Target) && entity.Target.Contains(".aspx"))
                    {
                        role.Menus.Add(entity);
                    }
                }
            }

            if (pageList != null)
            {
                var pages = dc.CreateQuery<AspxPage>("[AspxPages]");
                foreach (var page in pageList.Split(','))
                {
                    int pageID = int.Parse(page);
                    var entity = pages.First(p => p.PageID == pageID);
                    role.AspxPages.Add(entity);
                }
            }
        }

        /// <summary>
        /// 插入一个Role及其对应的page、menu和country
        /// </summary>
        public static void OnRoleInsertingCIO(ObjectContext dc, Role role, string pageList, string menuList, string countryList)
        {
            role.BelongsTo = SystemModule.CIO.ToString();
            if (menuList != null)
            {
                var menus = dc.CreateQuery<Menu>("[Menus]");
                foreach (var menu in menuList.Split(','))
                {
                    int menuID = int.Parse(menu);
                    var entity = menus.First(p => p.MenuID == menuID);
                    //判断menu是否为3级菜单，待修改
                    if (!String.IsNullOrEmpty(entity.Target) && entity.Target.Contains(".aspx"))
                    {
                        role.Menus.Add(entity);
                    }
                }
            }

            if (pageList != null)
            {
                var pages = dc.CreateQuery<AspxPage>("[AspxPages]");
                foreach (var page in pageList.Split(','))
                {
                    int pageID = int.Parse(page);
                    var entity = pages.First(p => p.PageID == pageID);
                    role.AspxPages.Add(entity);
                }
            }

            if (countryList != null)
            {
                var countries = dc.CreateQuery<Country>("[Countries]");
                foreach (var country in countryList.Split(','))
                {
                    int countryID = int.Parse(country);
                    var entity = countries.First(p => p.CountryID == countryID);
                    role.Countries.Add(entity);
                }
            }
        }

        /// <summary>
        /// 插入一个Role及其对应的page、menu和pcat
        /// </summary>
        public static void OnRoleInsertingCID(ObjectContext dc, Role role, string pageList, string menuList, string pcatList, string countryList)
        {
            role.BelongsTo = SystemModule.CID.ToString();
            if (menuList != null)
            {
                var menus = dc.CreateQuery<Menu>("[Menus]");
                foreach (var menu in menuList.Split(','))
                {
                    int menuID = int.Parse(menu);
                    var entity = menus.First(p => p.MenuID == menuID);
                    //判断menu是否为3级菜单，待修改
                    if (!String.IsNullOrEmpty(entity.Target) && entity.Target.Contains(".aspx"))
                    {
                        role.Menus.Add(entity);
                    }
                }
            }

            if (pageList != null)
            {
                var pages = dc.CreateQuery<AspxPage>("[AspxPages]");
                foreach (var page in pageList.Split(','))
                {
                    int pageID = int.Parse(page);
                    var entity = pages.First(p => p.PageID == pageID);
                    role.AspxPages.Add(entity);
                }
            }

            if (pcatList != null)
            {
                var pcats = dc.CreateQuery<PCAT>("[PCATs]");
                foreach (var pcatl in pcatList.Split(','))
                {
                    int pID = int.Parse(pcatl.Split(';')[0]);
                    int cID = int.Parse(pcatl.Split(';')[1]);
                    var entity = pcats.First(p => p.Province.ProvinceID == pID && p.Category.CateID == cID);
                    role.PCATs.Add(entity);
                }
            }
            if (countryList != null)
            {
                var countries = dc.CreateQuery<Country>("[Countries]");
                foreach (var country in countryList.Split(','))
                {
                    int countryID = int.Parse(country);
                    var entity = countries.First(p => p.CountryID == countryID);
                    role.Countries.Add(entity);
                }
            }
        }

        /// <summary>
        /// 修改一个Role对应的page和menu
        /// </summary>
        public static void OnRoleUpdating(ObjectContext dc, Role role, string pageList, string menuList, string belongsTo)
        {
            role.AspxPages.Load();
            role.AspxPages.Clear();

            role.Menus.Load();
            role.Menus.Clear();

            OnRoleInserting(dc, role, pageList, menuList, belongsTo);
        }

        /// <summary>
        /// 修改一个Role对应的page和menu、country
        /// </summary>
        public static void OnRoleUpdatingCIO(ObjectContext dc, Role role, string pageList, string menuList, string countryList)
        {
            role.AspxPages.Load();
            role.AspxPages.Clear();

            role.Menus.Load();
            role.Menus.Clear();

            role.Countries.Load();
            role.Countries.Clear();

            OnRoleInsertingCIO(dc, role, pageList, menuList, countryList);
        }

        /// <summary>
        /// 修改一个Role对应的page和menu、pacat
        /// </summary>
        public static void OnRoleUpdatingCID(ObjectContext dc, Role role, string pageList, string menuList, string pcatList, string countryList)
        {
            role.AspxPages.Load();
            role.AspxPages.Clear();

            role.Menus.Load();
            role.Menus.Clear();

            role.PCATs.Load();
            role.PCATs.Clear();

            role.Countries.Load();
            role.Countries.Clear();

            OnRoleInsertingCID(dc, role, pageList, menuList, pcatList, countryList);
        }

        /// <summary>
        /// 获取所有BelongsTo的值
        /// </summary>
        /// <returns></returns>
        public static IEnumerable GetAllBelongsTo()
        {
            return Enum.GetNames(typeof(SystemModule));
        }

        /// <summary>
        /// 通过RoleID和BelongsTo查询Pages
        /// </summary>
        public static IEnumerable GetPagesByRoleID(int roleID, string belongsTo)
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.RoleID == roleID);
                var pages = dc.AspxPages.Where(p => p.BelongsTo == belongsTo && p.Disabled == false).ToArray();
                var source = from p in pages
                             orderby p.FullName,p.AccessLevel
                             select new
                             {
                                 p.PageID,
                                 p.FullName,
                                 p.AccessLevel,
                                 CanAccess = GetAccess(p, role)
                             };
                var t = source.ToArray();
                return t;
            }
        }

        /// <summary>
        /// 通过RoleID和BelongsTo查询Menus
        /// </summary>
        public static IEnumerable GetMenusByRoleID(int roleID, string belongsTo)
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.RoleID == roleID);
                var menus = dc.Menus.Where(p => p.BelongsTo == belongsTo && p.Disabled == false && p.Parent != null).ToArray();
                var source = (from m in menus
                              orderby m.Sort
                             select new
                             {
                                 m.MenuID,
                                 m.Target,
                                 m.Name,
                                 Level = ShowLevel(GetLevel(m)),
                                 CanAccess = GetAccess(m, role),
                                 Disabled = ChkDisabled(m)
                             }).ToArray();
                //if (belongsTo == SystemModule.EZVisit.ToString() ||
                //    belongsTo == SystemModule.CCD.ToString() ||
                //    belongsTo == SystemModule.CCO.ToString())
                //{
                //    var commonMenus = dc.Menus.Where(p => p.BelongsTo == "" && p.Parent != null && p.Disabled == false).ToArray();
                //    var commonSource = (from m in commonMenus
                //              orderby m.Sort
                //              select new
                //              {
                //                  m.MenuID,
                //                  m.Target,
                //                  m.Name,
                //                  Level = ShowLevel(GetLevel(m)),
                //                  CanAccess = GetAccess(m, role),
                //                  Disabled = ChkDisabled(m)
                //              }).ToArray();
                //    var source1 = commonSource.Union(source);
                //    return source1;
                //}
                return source;
            }
        }
         
        /// <summary>
        /// 通过RoleID查询PCATs
        /// </summary>
        public static IEnumerable GetPCATsByRoleId(int roleID)
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.RoleID == roleID);
                var pcats = dc.PCATs.ToArray();
                var province = dc.Provinces.Where(p => p.Disabled == false).ToArray();
                var cate = dc.Categories.Where(p => p.Disabled == false).ToArray();
                var source = (from a in pcats
                              join b in province on a.ProvinceID equals b.ProvinceID 
                              join c in cate on a.CateID equals c.CateID
                              orderby a.ProvinceID
                             select new
                             {
                                 PName = b.Name,
                                 CName = c.Name,
                                 CanAccess = GetAccess(a, role),
                                 PCID = MakePCID(a)
                             }
                             ).ToArray() ;
                return source;
            }
        }


        /// <summary>
        /// 通过RoleID查询Countries
        /// </summary>
        public static IEnumerable GetCountriesByRoleId(int roleID)
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.RoleID == roleID);
                var country = dc.Countries.Where(p => p.Disabled == false).ToArray();
                var source = (from a in country
                              select new
                              {
                                  a.CountryID,
                                  a.Name,
                                  a.Description,
                                  CanAccess = GetAccess(a, role),
                              }).ToArray();
                return source;
            }
        }

        private static string GetAccess(PCAT pcat, Role role)
        {
            pcat.Roles.Load();
            return pcat.Roles.Contains(role) ? "checked" : "";
        }

        private static string GetAccess(Country c, Role r)
        {
            c.Roles.Load();
            return c.Roles.Contains(r) ? "checked" : "";
        }

        private static string GetAccess(AspxPage p, Role role)
        {
            p.Roles.Load();
            return p.Roles.Contains(role) ? "checked" : "";
        }

        private static string GetAccess(Menu m, Role role)
        {
            m.Roles.Load();
            return m.Roles.Contains(role) ? "checked" : "";
        }

        private static string MakePCID(PCAT p)
        {
            return p.ProvinceID.ToString() + ";" + p.CateID.ToString();
        }

        public static int GetLevel(Menu m)
        {
            m.ParentReference.Load();
            if (m.Parent == null)
                return 1;
            m.Parent.ParentReference.Load();
            if (m.Parent.Parent == null)
                return 2;
            else return 3;

            
        }

        private static string ChkDisabled(Menu m)
        {
            m.ParentReference.Load();
            if(m.Parent!=null)
                return m.Parent.Parent == null ? "hidden" : "checkbox";
            return "";
        }

        private static string ShowLevel(int level)
        {
            string str = "";
            for (; level > 2; level--)
                str += "&nbsp;&nbsp;&nbsp;&nbsp;";
            return str;
        }

        /// <summary>
        /// 将一个role的激活状态设为未激活
        /// </summary>
        public static void SetRoleDisabled(int roleID)
        {
            using (var dc = new CCEntities())
            {
                dc.Roles.FirstOrDefault(p => p.RoleID == roleID).Disabled = true;
                dc.SaveChanges();
            }
        }

        /// <summary>
        /// 根据当前ID获取Name
        /// </summary>
        public static IEnumerable getName(int entityID)
        {
            using (var dc = new CCEntities())
            {
                var name = dc.Roles.FirstOrDefault(p => p.RoleID == entityID).Name;
                return name;
            }
        }

        /// <summary>
        /// 重新绑定RoleInPage表
        /// </summary>
        public static void InsertRolePages(int roleid, string pagenames, string belongsto)
        {
            if (!String.IsNullOrEmpty(pagenames))
            {
                using (var dc = new CCEntities())
                {
                    if (roleid >= 0)
                    {
                        dc.SP_DeleteRoleInPageByRoleID(roleid, belongsto);
                        foreach (var page in pagenames.Split(','))
                        {
                            dc.SP_CreateRoleInPage(roleid, Convert.ToInt32(page));
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 重新绑定RoleInMenu表
        /// </summary>
        public static void InsertRoleMenu(int roleid, string menunames, string belongsto)
        {
            if (!String.IsNullOrEmpty(menunames))
            {
                using (var dc = new CCEntities())
                {
                    if (roleid >= 0)
                    {
                        dc.SP_DeleteRoleInMenuByRoleID(roleid, belongsto);
                        foreach (var page in menunames.Split(','))
                        {
                            dc.SP_CreateRoleInMenu(roleid, Convert.ToInt32(page));
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 重新绑定RoleInPCAT表
        /// </summary>
        public static void InsertRolePCat(int roleid, string pcatnames)
        {
            if (!String.IsNullOrEmpty(pcatnames))
            {
                using (var dc = new CCEntities())
                {
                    if (roleid >= 0)
                    {
                        dc.SP_DeleteRoleInPCATByRoleID(roleid);
                        foreach (var pcat in pcatnames.Split(','))
                        {
                            var pcat1 = pcat.Split(';');
                            dc.SP_CreateRoleInPCAT(roleid, Convert.ToInt32(pcat1[0]), Convert.ToInt32(pcat1[1]));
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 重新绑定RoleInCountry表
        /// </summary>
        public static void InsertRoleCountry(int roleid, string countrynames)
        {
            if (!String.IsNullOrEmpty(countrynames))
            {
                using (var dc = new CCEntities())
                {
                    if (roleid >= 0)
                    {
                        dc.SP_DeleteRoleInCountryByRoleID(roleid);
                        foreach (var country in countrynames.Split(','))
                        {
                            dc.SP_CreateRoleInCountry(roleid, Convert.ToInt32(country));
                        }
                    }

                }
            }
        }



        public static void InternalUpdateRole(ObjectContext dc, Role role, string pageList, string menuList, string pcatList, string countryList)
        {
            if (menuList != null)
            {
                var menus = dc.CreateQuery<Menu>("[Menus]");
                foreach (var menu in menuList.Split(','))
                {
                    int menuID = int.Parse(menu);
                    var entity = menus.First(p => p.MenuID == menuID);
                    //判断menu是否为3级菜单，待修改
                    if (!String.IsNullOrEmpty(entity.Target) && entity.Target.Contains(".aspx"))
                    {
                        role.Menus.Add(entity);
                    }
                }
            }

            if (pageList != null)
            {
                var pages = dc.CreateQuery<AspxPage>("[AspxPages]");
                foreach (var page in pageList.Split(','))
                {
                    int pageID = int.Parse(page);
                    var entity = pages.First(p => p.PageID == pageID);
                    role.AspxPages.Add(entity);
                }
            }

            if (pcatList != null)
            {
                var pcats = dc.CreateQuery<PCAT>("[PCATs]");
                foreach (var pcatl in pcatList.Split(','))
                {
                    int pID = int.Parse(pcatl.Split(';')[0]);
                    int cID = int.Parse(pcatl.Split(';')[1]);
                    var entity = pcats.First(p => p.Province.ProvinceID == pID && p.Category.CateID == cID);
                    role.PCATs.Add(entity);
                }
            }
            if (countryList != null)
            {
                var countries = dc.CreateQuery<Country>("[Countries]");
                foreach (var country in countryList.Split(','))
                {
                    int countryID = int.Parse(country);
                    var entity = countries.First(p => p.CountryID == countryID);
                    role.Countries.Add(entity);
                }
            }
        }


    }


}
